package com.example.zhinongbao.ui;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.zhinongbao.R;
import com.example.zhinongbao.adapter.MsgAdapter;
import com.example.zhinongbao.bean.Message;
import com.example.zhinongbao.utils.Constant;

import java.util.ArrayList;
import java.util.List;

/**
 * 聊天页面
 */
public class ChatFragment extends Fragment {
    // 消息列表
    private final List<Message> msg = new ArrayList<>();
    // 消息适配器
    private MsgAdapter msgAdapter;
    // 消息编辑框
    private EditText edit_msg;
    // 客户名字
    private TextView text_name;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_chat, container, false);
    }

    @Override
    public void onResume() {
        super.onResume();
        initView();
    }

    private void initView() {
        // 先把消息列表清空，然后加入当前客户发过来的消息
        msg.clear();
        msg.addAll(Constant.currentMsg);
        text_name = getView().findViewById(R.id.text_name);
        text_name.setText(Constant.currentChatPerson);
        edit_msg = getView().findViewById(R.id.edit_msg);
        getView().findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 把发送的消息放入消息列表中，通知数据更新，RecycleView更新视图
                msg.add(new Message(1, edit_msg.getText().toString()));
                msgAdapter.notifyDataSetChanged();
            }
        });

        RecyclerView chat_recycler_view = getView().findViewById(R.id.chat_recycler_view);
        LinearLayoutManager chatLayout = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        chat_recycler_view.setLayoutManager(chatLayout);
        msgAdapter = new MsgAdapter(msg);
        chat_recycler_view.setAdapter(msgAdapter);
    }

}
